package com.nail.api.customMake.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.nail.api.customMake.bean.FileUploadInfo;
import com.nail.api.customMake.bean.Indent;
import com.nail.api.customMake.dao.IFileUploadDao;
import com.nail.api.customMake.dao.IIndentDao;
import com.nail.api.customMake.dto.ImgDto;
import com.nail.api.customMake.service.IFileUploadService;
import com.nail.api.customMake.service.IInDentService;
import com.nail.api.user.bean.User;
import com.nail.common.Constant;
import com.nail.service.impl.BaseService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.*;


@Service("fileUploadService")
public class FileUploadServiceImpl extends BaseService implements IFileUploadService {
	Logger logger = Logger.getLogger(this.getClass());
	
    @Autowired
    private IFileUploadDao fileUploadDao;

    @Autowired
    private IIndentDao indentDao;

    @Transactional
    public void insertFileUploadInfo(FileUploadInfo fileUploadInfo){
        fileUploadDao.insertSelective(fileUploadInfo);
    }


    @Transactional
    public List<FileUploadInfo> uploadImgBase64(String imgList, User user,String imgRootPath){
        List<ImgDto> imgDtos = JSONArray.parseArray(imgList, ImgDto.class);
        List<FileUploadInfo> uploadInfos = new ArrayList<FileUploadInfo>();
        for (ImgDto imgDto : imgDtos) {
            StringBuffer name = new StringBuffer();

            String userName = user.getUserName();

            //新建一个用户专属文件夹 File/img/{userName}/{moth}/
            String userPath = imgRootPath  + userName + getMonthFilePath();
            File userFile = new File(userPath);
            if (userFile != null && !userFile.exists()) {
                userFile.mkdirs();
            }

            // 重命名文件
            name.append(UUID.randomUUID().toString().replace("-", ""))
                    .append(imgDto.getImgName().substring(imgDto.getImgName().indexOf(".")));

            String file = userPath + name;

            //图片开头 data:image/png;base64, 等。。。。
            String imgData = imgDto.getImgData();
            if(imgData.contains(";base64,")){
                imgData = imgData.substring(imgData.indexOf(";base64,")+8, imgData.length()-1);
            }
            GenerateImage(imgData,file);

            FileUploadInfo uploadInfo = new FileUploadInfo();
            uploadInfo.setFileName(imgDto.getImgName());
            uploadInfo.setPath(file);
            uploadInfo.setCreateTime(new Date());
            uploadInfo.setUserId(user.getId());
            uploadInfo.setUserName(user.getUserName());
            fileUploadDao.insertSelective(uploadInfo);
            uploadInfos.add(uploadInfo);
        }
        return uploadInfos;
    }

    public FileUploadInfo getImg(Long id){
        return fileUploadDao.selectByPrimaryKey(id);
    }

    public List<FileUploadInfo> getFileUploadInfoByOrderId(String orderId){
        Indent indent = indentDao.getIndentByOrderId(orderId);
        if(indent.getImgIds().replaceAll(",", "").length() > 0){
        	String ids ="";
        	for (String str : indent.getImgIds().split(",")) {
				if(!StringUtils.isEmpty(str)){
					ids += str + ",";
				}
			}
        	if(ids.endsWith(",")){
        		ids = ids.substring(0, ids.length()-1);
        	}
            return fileUploadDao.getFileUploadInfoByIds(ids);
        }
        return null;
    }


    // ----------------------------- 方法 --------------------------------------

    /**
     * 获取图片名称 例如：2017/09/05
     *
     * @return
     */
    private String getMonthAndDayFilePath(String imgRootPath) {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        String monthStr;
        if (month < 10) {
            monthStr = "0" + month;
        } else {
            monthStr = String.valueOf(month);
        }
        return imgRootPath + year + "/" + monthStr + "/";
    }

    private String getMonthFilePath() {
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;
        String monthStr;
        if (month < 10) {
            monthStr = "0" + month;
        } else {
            monthStr = String.valueOf(month);
        }
        return "/" + monthStr + "/";
    }

    //图片转化成base64字符串
    public String GetImageStr(InputStream inputStream) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e);
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    //base64字符串转化成图片
    public boolean GenerateImage(String imgStr, String path) {
        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            //新生成的图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
